#include<stdio.h>
#include<pthread.h>
#include<unistd.h>

#define NUM 10000 
int tickets = NUM; // 临界资源 
pthread_mutex_t mutex; //1)定义互斥锁

void *ticket_get(void *arg)
{
  int number = (int)arg;
  //const char* name = (char*)arg;  
  while(1)
  {
    pthread_mutex_lock(&mutex);//3)上锁,会影响性能
    if(tickets > 0){
      printf("thread [%d] ticket : %d\n", number, tickets--);
      usleep(100);
     // printf("[%s] num ticket: %d\n", name, tickets--);//tickets--是临界区，不是原子的
      pthread_mutex_unlock(&mutex);//4)解锁
    }
    else
    {
      pthread_mutex_unlock(&mutex);
      break;
    }
  }

  // printf("%s quit!\n", name);
  pthread_exit((void*)0);
}

int main()
{
  pthread_t tid[5];
  pthread_mutex_init(&mutex, NULL);//2) 初始化
  for(int i = 0; i < 5; i++){
    pthread_create(&tid[i], NULL, ticket_get, (void*)i);
  }

  for(int i =0; i < 5; i++){
    pthread_join(tid[i],NULL);
  }
  pthread_mutex_destroy(&mutex);//5)释放锁
  
  //while(1){
  //  printf("I am main thread!,pid: %d \n",getppid());
  //  sleep(2);
  //}
  return 0;
}
